package com.hatricks.is.algorithm.abc;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class PrintABC2 {

    private static final Object LOCK = new Object();
    private static int state = 0;

    public static void main(String[] args) {
        Thread threadA = new Thread(new PrintTask("a", 0));
        Thread threadB = new Thread(new PrintTask("b", 1));
        Thread threadC = new Thread(new PrintTask("c", 2));

        threadA.start();
        threadB.start();
        threadC.start();

    }

    static class PrintTask implements Runnable {
        private String letter;
        private int targetState;

        public PrintTask(String letter, int targetState) {
            this.letter = letter;
            this.targetState = targetState;
        }

        @SneakyThrows
        @Override
        public void run() {
            for (int i = 0; i < 10; ) {
                synchronized (LOCK) {
                    try {
                        while (state % 3 != targetState) {
                            LOCK.wait();
                        }
                        System.out.println(letter);
                        state++;
                        i++;
                        LOCK.notifyAll();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
